package GUI;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

import engine.ChessEngine;

public class EnginesManager {
	private File file;
	ArrayList<ChessEngine> engines=null;
	
	public EnginesManager(File file) throws IOException{
		this.file= file;
		engines = new ArrayList<ChessEngine>();
		loadFromFile();
	}
	
	public void addEngine(String path) throws Exception{
		engines.add(new ChessEngine(path));
		saveFile();
	}
	
	public void deleteEngine(ChessEngine engine) throws Exception{
		engines.remove(engine);
		saveFile();
	}
	
	private void loadFromFile() throws IOException{
		FileReader readFile = new FileReader(file);		
		BufferedReader input = new BufferedReader(readFile);
		
		 String line = null; 
	     while ((line = input.readLine()) != null){
	          try{
	        	  engines.add(new ChessEngine(line));
	          }catch(Exception e){
	        	  
	          }
	     }
		
	}
	
	private void saveFile() throws IOException{
		FileWriter outFile = new FileWriter(this.file);
		PrintWriter out = new PrintWriter(outFile);
		for(ChessEngine engine: engines)
			out.println(engine.getPath());
		
		 out.close();
		 outFile.close();
	}
	

	public ArrayList<ChessEngine> getEngines() {
		return engines;
	}
	
}
